package com.styytech.dadabao.ui.project;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.loopj.android.http.RequestParams;
import com.styytech.dadabao.DadaApplication;
import com.styytech.dadabao.R;
import com.styytech.dadabao.api.requestresult.CommonResult;
import com.styytech.dadabao.api.requestresult.InvestmentAmountResult;
import com.styytech.dadabao.api.response.AbstractResponseResult;
import com.styytech.dadabao.api.templates.HttpRequest;
import com.styytech.dadabao.base.BaseActivity;
import com.styytech.dadabao.bean.InvestmentAmount;
import com.styytech.dadabao.constant.ConstantsServerUrl;
import com.styytech.dadabao.exception.ArgumentsException;
import com.styytech.dadabao.exception.RequestException;
import com.styytech.dadabao.ui.main.MainActivity;
import com.styytech.dadabao.ui.my.RechargeActivity;
import com.styytech.dadabao.ui.my.accountset.PayforSetActivity;
import com.styytech.dadabao.utils.CommonUtils;
import com.styytech.dadabao.utils.ParseJsonUtils;
import com.styytech.dadabao.utils.SpUser;
import com.styytech.dadabao.widge.dialog.CustomLoadingDialog;
import com.styytech.dadabao.widge.dialog.EnsureDialog;
import com.styytech.dadabao.widge.dialog.JobNumDialog;
import com.styytech.dadabao.widge.dialog.PassWordDialog;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

/**
 * Created by User on 2015/8/18.
 */
@ContentView(R.layout.activity_investment_amount)
public class InvestmentAmountActivity extends BaseActivity implements View.OnClickListener {
    //项目可投金额
    @ViewInject(R.id.tv_leftCredit)
    private TextView tv_leftCredit;
    //可用金额
    @ViewInject(R.id.tv_accountBalance)
    private TextView tv_accountBalance;
    //可用优惠券
    @ViewInject(R.id.tv_coupon)
    private TextView tv_coupon;
    //投资金额
    @ViewInject(R.id.edt_money)
    private EditText edt_money;
    @ViewInject(R.id.tv_wrong)
    private TextView tv_wrong;
    //共需支付
    @ViewInject(R.id.tv_final_money)
    private TextView tv_final_money;
    //确认支付
    @ViewInject(R.id.bt_ensure_aplay)
    private Button bt_ensure_aplay;
    private String search_Id;
    @ViewInject(R.id.llyt_main)
    private RelativeLayout llyt_main;
    //正确提示
    @ViewInject(R.id.rlyt_right)
    private RelativeLayout rlyt_right;
    @ViewInject(R.id.rlyt_wrong)
    private RelativeLayout rlyt_wrong;
    //工号
    @ViewInject(R.id.et_job_number)
    private EditText et_job_number;
    //匹配工号
    @ViewInject(R.id.bt_yz_jobnum)
    private Button bt_yz_jobnum;
    //项目可投金额
    private Double leftCredit;
    //项目可投金额
    private String leftCreditF;
    //账户可用余额
    private Double accountBalance;
    //可用优惠卷
    private Double coupon;
    //需充值
    private Double final_money;
    //起投金额
    private Double start_money;
    //跟投金额
    private Double second_money;
    private String password;
    private Double money_double;
    private String money_string;
    EnsureDialog ensureDialog;
    EnsureDialog passwordDialog;

    JobNumDialog searchJobNumber;
    PassWordDialog checkDialog;
    private CustomLoadingDialog mdlg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        super.onCreate(savedInstanceState);
        Intent intent=getIntent();
        Bundle bundle=intent.getExtras();
        search_Id=bundle.getString("id");
        initViews();


    }

    @Override
    protected void onResume() {
        super.onResume();
        if (SpUser.getUserToken(this) != null && !SpUser.getUserToken(this).equals("")) {
            getInvestmentAmount();
        }
    }

    private void setToastVisible(int wrong,int right){
        rlyt_wrong.setVisibility(wrong);
        rlyt_right.setVisibility(right);
    }
    private void initViews() {
        setToastVisible(View.VISIBLE, View.INVISIBLE);
        DadaApplication.addActivity(this);
        setTopBar("投资金额", View.VISIBLE, View.VISIBLE, "取消");
        edt_money.addTextChangedListener(new NumWatcher(edt_money));
        et_job_number.addTextChangedListener(new NumWatchers(et_job_number));
        bt_ensure_aplay.setOnClickListener(this);
        bt_yz_jobnum.setOnClickListener(this);
        et_job_number.setOnClickListener(this);
        bt_yz_jobnum.setClickable(false);
        bt_ensure_aplay.setClickable(false);
        getInvestmentAmount();

    }
    protected void reloadBtnOnclick(){
        getInvestmentAmount();
    }
    private void getInvestmentAmount(){

        llyt_main.setVisibility(View.GONE);
        setView(View.VISIBLE, View.VISIBLE, View.VISIBLE, View.GONE, "正在获取数据，请稍等...");

        String url = ConstantsServerUrl.getInvestmentAmountUrl();
        RequestParams params = new RequestParams();
        params.put("productId", search_Id);
        params.put("token", SpUser.getUserToken(this));

        InvestmentAmountResult logResult = new InvestmentAmountResult(responseResult);
        try {
            new HttpRequest(this).doPost(logResult,url,params);
        } catch (ArgumentsException e) {
            Log.i("INFO","1e:"+e);
            e.printStackTrace();
        } catch (RequestException e) {
            Log.i("INFO","2e:"+e);
            e.printStackTrace();
        }
    }
    /**
     * 获取推荐结果处理
     */
    AbstractResponseResult responseResult = new AbstractResponseResult() {

        @Override
        public void executeSuccess(Object object) {
            // TODO
            Log.e("asd", "object---" + object);
            llyt_main.setVisibility(View.VISIBLE);
            setView(View.GONE, View.VISIBLE, View.VISIBLE, View.GONE,"正在获取数据，请稍等...");
            setUpViews(object);
        }

        @Override
        public void executeError(String message, int errorCode) {
            CommonUtils.showToastMsg(InvestmentAmountActivity.this, "" + message);
            setView(View.VISIBLE, View.GONE, View.VISIBLE, View.VISIBLE, ""+message);
        }

        @Override
        public void HttpError(String message, int errorCode) {
            CommonUtils.showToastMsg(InvestmentAmountActivity.this, "" + message);
            setView(View.VISIBLE, View.GONE, View.VISIBLE, View.VISIBLE, ""+message);
        }
    };
    private void setUpViews(Object object){
        InvestmentAmount investmentAmount=(InvestmentAmount)object;
        //项目可投金额
       // if(investmentAmount.getLeftCredit()!=0){
            leftCredit=investmentAmount.getLeftCredit();
            leftCreditF=investmentAmount.getLeftCreditF();
            if (leftCreditF.equals("")){
                tv_leftCredit.setText("0");
            }else{
                tv_leftCredit.setText(leftCreditF);
            }

      //  }
        //账户余额
        if(investmentAmount.getAccountBalance()!=0){
            accountBalance=investmentAmount.getAccountBalance();
            String ss=investmentAmount.getAccountBalanceF();
            Log.e("asd","---------"+accountBalance+"");
            Log.e("asd","---------"+ss);
            tv_accountBalance.setText(ss);
        }else{
            accountBalance=(double)0;
            tv_accountBalance.setText("0");
        }

        //可用优惠卷
        if(investmentAmount.getCoupon()!=0){
            coupon=investmentAmount.getCoupon();
            tv_coupon.setText(coupon+"");
        }
       // if(investmentAmount.getInceptMoney()!=0){
            start_money=investmentAmount.getInceptMoney();
      //  }
        if(investmentAmount.getStepMoney()!=0){
            second_money=investmentAmount.getStepMoney();
        }
        String s1s=formatTosepara(start_money);
        tv_wrong.setText("该项目起投金额为"+s1s+"元");

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.bt_ensure_aplay:
                //先要判断是否设置支付密码
                if(SpUser.getBuyPasswordStatus(this)==0){
                    showPassWordDialog();
                }else{
                    // 确认支付判断余额是否够投资
                    if(final_money>0){
                        //去充值
                        showDialog();
                    }else{
                        //直接去调支付
                        money_string=subZeroAndDot(edt_money.getText().toString());
                        money_double = Double.parseDouble(money_string);
                        showCheckDialog();
                    }
                }
                break;
            case R.id.bt_yz_jobnum:
                search_JobNum();

                break;
            case R.id.et_job_number:
                et_job_number.setFocusableInTouchMode(true);
                et_job_number.requestFocus();
                break;
        }
    }

    //余额不足是否投资
    private void showDialog(){
        ensureDialog = new EnsureDialog(this, "提示", "余额不足，是否去充值？", 1,"确定");
        ensureDialog.setEnsureDialogCallback(ensureDialogcallback);
        ensureDialog.setCanceleDialogCallback(cancelDialogcallback);
        //如果强制升级(点其他位置或back不能取消)
        ensureDialog.NotCancel(false);
        ensureDialog.show();
    }
    //您尚未设置支付密码，是否立即设置？
    private void showPassWordDialog(){
        passwordDialog = new EnsureDialog(this, "提示", "您尚未设置支付密码，是否立即设置？", 1,"确定");
        passwordDialog.setEnsureDialogCallback(ensurePassDialogcallback);
        passwordDialog.setCanceleDialogCallback(cancelPassDialogcallback);
        //如果强制升级(点其他位置或back不能取消)
        passwordDialog.NotCancel(false);
        passwordDialog.show();
    }
    //验证支付密码
    private void showCheckDialog(){
        checkDialog = new PassWordDialog(this,money_string);
        checkDialog.setEnsureDialogCallback(ensurecallback);
        checkDialog.setCanceleDialogCallback(cancelcallback);
        checkDialog.NotCancel(false);
        checkDialog.show();
    }

    /**
     * 设置充值dialog需要处理的事情
     */
    EnsureDialog.Dialogcallback ensureDialogcallback = new EnsureDialog.Dialogcallback() {
        @Override
        public void dialogdo() {
            startActivity(new Intent(InvestmentAmountActivity.this, RechargeActivity.class));

            ensureDialog.dismiss();

        }
    };
    EnsureDialog.Dialogcallback cancelDialogcallback = new EnsureDialog.Dialogcallback() {
        @Override
        public void dialogdo() {
            ensureDialog.dismiss();

        }
    };

    /**
     * 设置支付密码Dialog需要处理的事情
     */
    EnsureDialog.Dialogcallback ensurePassDialogcallback = new EnsureDialog.Dialogcallback() {
        @Override
        public void dialogdo() {

            startActivity(new Intent(InvestmentAmountActivity.this, PayforSetActivity.class));
            passwordDialog.dismiss();

        }
    };
    EnsureDialog.Dialogcallback cancelPassDialogcallback = new EnsureDialog.Dialogcallback() {
        @Override
        public void dialogdo() {
            passwordDialog.dismiss();

        }
    };
    /**
     * 验证支付密码
     */
    PassWordDialog.Dialogcallback ensurecallback = new PassWordDialog.Dialogcallback() {
        @Override
        public void dialogdo() {

           password=checkDialog.getPassword_string();
            if (password.equals("")){
                CommonUtils.showToastMsg(InvestmentAmountActivity.this, "请输入支付密码!");
            }else{
                buyProject();
                checkDialog.dismiss();
            }


        }
    };
    PassWordDialog.Dialogcallback cancelcallback = new PassWordDialog.Dialogcallback() {
        @Override
        public void dialogdo() {
            checkDialog.dismiss();

        }
    };
    //支付
    private void buyProject(){
        mdlg=new CustomLoadingDialog(this,"购买","支付中...",false);
        mdlg.show();
        String url = ConstantsServerUrl.getBuyUrl();
        RequestParams params = new RequestParams();
        params.put("token",SpUser.getUserToken(this));
        params.put("productId", search_Id);
        params.put("money",money_double);
        params.put("payPassword",password);
        params.put("memberNo",et_job_number.getText().toString());

        CommonResult logResult = new CommonResult(buyResult);
        try {
            new HttpRequest(this).doPost(logResult,url,params);
        } catch (ArgumentsException e) {
            Log.i("INFO","1e:"+e);
            e.printStackTrace();
        } catch (RequestException e) {
            Log.i("INFO","2e:"+e);
            e.printStackTrace();
        }
    }
    /**
     * 支付结果处理
     */
    AbstractResponseResult buyResult = new AbstractResponseResult() {

        @Override
        public void executeSuccess(Object object) {
            // TODO
            mdlg.dismiss();
            CommonUtils.showToastMsg(InvestmentAmountActivity.this, "购买成功");
           // getInvestmentAmount();
            startActivity(new Intent(InvestmentAmountActivity.this,BuySuccessActivity.class));
            finish();
        }

        @Override
        public void executeError(String message, int errorCode) {
            mdlg.dismiss();
            CommonUtils.showToastMsg(InvestmentAmountActivity.this, "" + message);
        }

        @Override
        public void HttpError(String message, int errorCode) {
            mdlg.dismiss();
            CommonUtils.showToastMsg(InvestmentAmountActivity.this, "" + message);
        }
    };
    //验证工号
    private void search_JobNum(){
        mdlg=new CustomLoadingDialog(this,"工号","匹配中...",false);
        mdlg.show();
        String url = ConstantsServerUrl.getSearchJobNum();
        RequestParams params = new RequestParams();
        params.put("token",SpUser.getUserToken(this));
        params.put("memberNo",et_job_number.getText().toString());
        CommonResult logResult = new CommonResult(jobNumResult);
        try {
            new HttpRequest(this).doPost(logResult,url,params);
        } catch (ArgumentsException e) {
            Log.i("INFO","1e:"+e);
            e.printStackTrace();
        } catch (RequestException e) {
            Log.i("INFO","2e:"+e);
            e.printStackTrace();
        }
    }
    //验证工号结果
    private void showJobNumDialog(String string){
        searchJobNumber = new JobNumDialog(this, string);
        searchJobNumber.setEnsureDialogCallback(canleJobNumCallback);
        searchJobNumber.setCanceleDialogCallback(canleJobNumCallback);
        //如果强制升级(点其他位置或back不能取消)
        searchJobNumber.NotCancel(false);
        searchJobNumber.show();
    }
    JobNumDialog.Dialogcallback canleJobNumCallback = new JobNumDialog.Dialogcallback() {
        @Override
        public void dialogdo() {
            searchJobNumber.dismiss();

        }
    };
    /**
     * 验证工号结果处理
     */
    AbstractResponseResult jobNumResult = new AbstractResponseResult() {

        @Override
        public void executeSuccess(Object object) {
            JSONArray jsonArray = (JSONArray) object;
           try{
                    JSONObject jsonObjectApp = jsonArray.getJSONObject(0);
                    String name=jsonObjectApp.has("name") ? jsonObjectApp.getString("name")
                            : "";
                    if (!name.equals("")){
                        showJobNumDialog(name);
                    }

           }catch (Exception e){
               e.printStackTrace();
           }

            // TODO
            mdlg.dismiss();

        }

        @Override
        public void executeError(String message, int errorCode) {
            mdlg.dismiss();
            showJobNumDialog("");
           // CommonUtils.showToastMsg(InvestmentAmountActivity.this, "" + message);
        }

        @Override
        public void HttpError(String message, int errorCode) {
            mdlg.dismiss();
            CommonUtils.showToastMsg(InvestmentAmountActivity.this, "" + message);
        }
    };
    class NumWatcher implements TextWatcher {

        // 监听改变的文本框
        private EditText editText;
        private int editStart;
        private int editEnd;


        /**
         * 构造函数
         */
        public NumWatcher(EditText editText) {
            this.editText = editText;

        }

        @Override
        public void onTextChanged(CharSequence string, int start, int before,
                                  int count) {
            String editable = editText.getText().toString();
            if (string.toString().equals(".")){
               /* editText.setText(".");
                tv_wrong.setText("输入金额不合法，重新输入");*/
                return;
            }else{
                if (string.toString().contains(".")) {
                    if (string.length() - 1 - string.toString().indexOf(".") > 2) {
                        string = string.toString().subSequence(0,
                                string.toString().indexOf(".") + 3);
                        editText.setText(string);
                        editText.setSelection(string.length());
                    }
                }
                if (string.toString().trim().substring(0).equals(".")) {
                    string = "0" + string;
                    editText.setText(string);
                    editText.setSelection(2);
                }

                if (string.toString().startsWith("0")
                        && string.toString().trim().length() > 1) {
                    if (!string.toString().substring(1, 2).equals(".")) {
                        editText.setText(string.subSequence(0, 1));
                        editText.setSelection(1);
                        return;
                    }
                }
            }

            /*String str = stringFilter(editable.toString());
            if (!editable.equals(str)) {
                editText.setText(str);
                // 设置新的光标所在位置 www.2cto.com editText.setSelection(str.length());
                Toast.makeText(InvestmentAmountActivity.this, "输入字符无意义!",
                        Toast.LENGTH_SHORT).show();
            }*/

        }

        @Override
        public void afterTextChanged(Editable s) {
            editStart = edt_money.getSelectionStart();
            editEnd = edt_money.getSelectionEnd();
            if (!s.toString().equals("")) {
                if (s.toString().equals(".")){
                    s.delete(editStart - 1, editEnd);
                    int tempSelection = editStart;
                    edt_money.setText(s.toString());
                    edt_money.setSelection(tempSelection);
                    tv_wrong.setText("输入金额不合法，重新输入");
                    return;
                }else{
                    double now_money=Double.parseDouble(s.toString());
                    if (now_money<start_money){
                        setToastVisible(View.VISIBLE,View.INVISIBLE);
                        //String s1=formatTosepara(Float.parseFloat(start_money+""));
                        String s1=formatTosepara(start_money);
                        tv_wrong.setText("该项目起投金额为"+s1+"元");
                        bt_ensure_aplay.setBackgroundColor(Color.parseColor("#CDC9C9"));
                        bt_ensure_aplay.setClickable(false);
                    }else if (now_money>=start_money&&((now_money-start_money)%second_money!=0)){
                        setToastVisible(View.VISIBLE,View.INVISIBLE);
                        String s2=formatTosepara(second_money);
                        tv_wrong.setText("您跟投的金额必须是" + s2 + "的倍数");
                        bt_ensure_aplay.setBackgroundColor(Color.parseColor("#CDC9C9"));
                        bt_ensure_aplay.setClickable(false);
                    } else if (now_money > leftCredit) {
                        setToastVisible(View.VISIBLE,View.INVISIBLE);
                        Toast.makeText(InvestmentAmountActivity.this, "超过项目可投金额",
                                Toast.LENGTH_SHORT).show();
                        //tv_wrong.setText("超过项目可投金额，最多只能投"+leftCredit+"元");
                        s.delete(editStart - 1, editEnd);
                        int tempSelection = editStart;
                        edt_money.setText(s.toString());
                        edt_money.setSelection(tempSelection);
                       // bt_ensure_aplay.setBackgroundColor(Color.parseColor("#CDC9C9"));
                        //bt_ensure_aplay.setClickable(false);
                    }else{
                        // 投资金额
                        setToastVisible(View.INVISIBLE,View.VISIBLE);
                        double money_num = Double.parseDouble(s
                                .toString());
                        final_money=money_num-accountBalance;
                       /* if (final_money>0){
                            setText(tv_final_money,final_money+"");
                        }else {
                            setText(tv_final_money,"0");
                        }*/
                        String s2=formatTosepara(money_num);
                        setText(tv_final_money,s2);
                        bt_ensure_aplay.setBackgroundColor(Color.parseColor("#f65403"));
                        bt_ensure_aplay.setClickable(true);

                    }
                }
            }else{
                setToastVisible(View.VISIBLE,View.INVISIBLE);
                String s2=formatTosepara(start_money);
                tv_wrong.setText("该项目起投金额为"+s2+"元");
            }

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {

        }

    }
    private void setText(TextView text,String string){
        Log.e("dasd","-----------"+string);
        String strings=subZeroAndDot(string);
        Log.e("dasd", "-----------" + strings);
        text.setText(strings);

    }
    //去掉小数点后多余的0
    public static String subZeroAndDot(String s){
        if(s.indexOf(".") > 0){
            s = s.replaceAll("0+?$", "");//去掉多余的0
            s = s.replaceAll("[.]$", "");//如最后一位是.则去掉
        }
        return s;
    }
    public static String stringFilter(String str) throws PatternSyntaxException {
        // 只允许字母和数字
        String regEx = "^[^[1-9]]\\d*";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("").trim();
    }
    public static String formatTosepara(double data) {
        DecimalFormat df = new DecimalFormat("##,##0.00");
        return df.format(data);
    }
    class NumWatchers implements TextWatcher {

        // 监听改变的文本框
        private EditText editText;
        private int editStart;
        private int editEnd;

        /**
         * 构造函数
         */
        public NumWatchers(EditText editText) {
            this.editText = editText;

        }
        @Override
        public void onTextChanged(CharSequence string, int start, int before,
                                  int count) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (!et_job_number.getText().toString().equals("")){
                bt_yz_jobnum.setBackgroundColor(Color.parseColor("#f65403"));
                bt_yz_jobnum.setClickable(true);
            }else {
                bt_yz_jobnum.setBackgroundColor(Color.parseColor("#CDC9C9"));
                bt_yz_jobnum.setClickable(false);
            }

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {

        }

    }
}
